package com.wooophone.buyi.web.action;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;

import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;

import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;

import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.wooophone.buyi.bean.EmailValidation;
import com.wooophone.buyi.bean.OAuth;
import com.wooophone.buyi.bean.User;
import com.wooophone.buyi.bean.WeiboUser;
import com.wooophone.buyi.biz.EmailValidationBiz;
import com.wooophone.buyi.biz.OAuthBiz;
import com.wooophone.buyi.biz.UserBiz;
import com.wooophone.buyi.biz.WeiboUserBiz;
import com.wooophone.common.email.TemplateEmailService;
import com.wooophone.common.util.JsonSfUtil;
import com.wooophone.common.util.MatcheUtil;
import com.wooophone.common.util.Md5Util;
import com.wooophone.common.web.action.BaseAction;

public class AccountAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private static final int ACCOUNT_LOG_COOKIE_MAXAGE = 3600 * 24 * 7;

	private String code;
	private OAuth oauth;

	@Autowired
	private OAuthBiz oAuthBiz;
	@Autowired
	private WeiboUserBiz weiboUserBiz;
	@Autowired
	private UserBiz userBiz;

	@Autowired
	TemplateEmailService templateEmailService;
	@Autowired
	EmailValidationBiz emailValidationBiz;

	private WeiboUser weiboUser;

	private User user;
	private String name;
	private String userName;
	private String password;

	private String uid;
	private String vid;

	/**
	 * 用得当前登陆的用户信息
	 * 
	 * @return
	 */
	public String getAccount() {

		String sessionId = getCookie(SESSION_ID);
		if (sessionId == null) {
			sessionId = getRequest().getSession().getId();
			setCookie(SESSION_ID, sessionId, ACCOUNT_LOG_COOKIE_MAXAGE);
		}
		oauth = sessionId == null ? null : oAuthBiz.getBySessionId(sessionId);

		if (oauth == null || oauth.getUser() == null) {
			return ajax(toCallBackErrorString("用户不存在"));
		}

		return ajax(toCallBackString(JsonSfUtil
				.toJsonByReject(oauth, "currentLoginDate", "lastLoginDate",
						"createDate", "modifyDate")));
	}

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "user.userName", message = "用户名必填!"),
			@RequiredStringValidator(fieldName = "user.password", message = "密码必填!"),
			@RequiredStringValidator(fieldName = "user.email", message = "邮箱必填!"), })
	public String register() {
		// 如果用户已存在
		if (userBiz.existByEmail(user.getEmail())) {
			clearActionErrors();
			addActionError("该邮箱已被注册过!");
			return INPUT;
		}

		if (userBiz.existByUserName(user.getUserName())) {
			addActionError("该用户名已被注册过!");
			return INPUT;
		}

		// 新用户
		this.user.setPassword(Md5Util.getMD5Str(this.user.getPassword()));
		userBiz.save(this.user);
		// acceptLogin(this.user);

		return SUCCESS;
	}

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "user.userName", message = "用户名必填!"),
			@RequiredStringValidator(fieldName = "user.password", message = "密码必填!"), })
	public String weiboRegister() {
		// 如果用户已存在

		// 第三方用户注册
		User user = userBiz.get(this.user.getId());

		if (!user.getUserName().equals(this.user.getUserName())) {
			if (userBiz.existByUserName(user.getUserName())) {
				addActionError("该用户名已被注册过!");
				return INPUT;
			}
		}

		user.setUserName(this.user.getUserName());
		user.setPassword(Md5Util.getMD5Str(this.getUser().getPassword()));

		WeiboUser weiboUser = weiboUserBiz.get(user.getWeiboUserId());
		weiboUser.setRegistered(true);
		weiboUserBiz.update(weiboUser);

		user.setValidation(true);
		user.setWeiboUserId(weiboUser.getId());
		user.setHeadPortrait(weiboUser.getAvatarLarge());

		userBiz.update(user);
		acceptLogin(user);

		return SUCCESS;
	}

	/**
	 * 登陆
	 * 
	 * @return
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "userName", message = "用户名必填!"),
			@RequiredStringValidator(fieldName = "password", message = "密码必填!") })
	public String login() {
		if (MatcheUtil.matcheEmail(userName)) {
			user = userBiz.getByEmail(userName);
		} else {
			user = userBiz.getByUserName(userName);
		}

		if (user == null) {
			clearActionErrors();
			addActionError("该用户不存在！");
			return INPUT;
		}

		if (Md5Util.getMD5Str(password).equals(user.getPassword())) {
			// 检查用户是否已验证过
			if (!user.isValidation()) {
				acceptLogin(user);
				return "home";
			} else {
				// 去发送邮箱验证
				return "email_validation";
			}
		} else {
			addActionError("用户名或密码错误！");
			return INPUT;
		}
	}

	@Validations(requiredStrings = { @RequiredStringValidator(fieldName = "id", message = "ID is null!") })
	public String sendEmailValidation() {

		final User user = userBiz.get(id);

		if (user == null) {
			addActionError("用户不存在");
			return ERROR;
		}

		EmailValidation emailValidation = new EmailValidation();
		emailValidation.setExpiration(System.currentTimeMillis() + 3 * 24
				* 3600 * 1000);
		emailValidation.setUserId(id);
		emailValidationBiz.save(emailValidation);

		if (emailValidation.getId() != null) {
			final Map<String, Object> map = new HashMap<String, Object>();
			map.put("username", user.getUserName());
			map.put("id", user.getId());
			map.put("vid", emailValidation.getId());
			map.put("base", getBasepath());

			// 启动发送邮件的线程，以免耗费太多时间
			new Thread() {
				public void run() {
					try {
						templateEmailService.sendTemplateHtmlMail(map,
								"布依在线验证邮件", user.getEmail(),
								"email_validation.ftl");
					} catch (MessagingException e) {
						e.printStackTrace();
					} catch (EmailException e) {
						e.printStackTrace();
					}
				};
			}.start();

			return SUCCESS;
		} else {
			addActionError("出现错误！");
			return "login";
		}
	}

	/**
	 * 邮箱验证
	 * 
	 * @return
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "id", message = "ID is null!"),
			@RequiredStringValidator(fieldName = "vid", message = "VID is null!") })
	public String emailValidation() {
		try {
			EmailValidation emailValidation = emailValidationBiz.get(vid);
			User user = userBiz.get(id);
			if (emailValidation != null
					&& user != null
					&& emailValidation.getExpiration() > System
							.currentTimeMillis()) {
				// 验证通过
				user.setValidation(true);
				userBiz.save(user);
				// 接受登陆
				acceptLogin(user);
				return SUCCESS;
			} else {
				return INPUT;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 接受登陆
	 * 
	 * @param user
	 */
	public void acceptLogin(User user) {

		String sessionId = getCookie(SESSION_ID);
		if (sessionId != null) {
			oauth = oAuthBiz.getBySessionId(sessionId);
		}

		if (oauth == null) {
			oauth = new OAuth();
			oauth.setUser(user);
			sessionId = getRequest().getSession().getId();
			oauth.setSessionId(sessionId);
		}

		setCookie(SESSION_ID, sessionId, ACCOUNT_LOG_COOKIE_MAXAGE);

		oAuthBiz.save(oauth);

	}

	/**
	 * 微博登陆
	 * 
	 * @return
	 */
	public String weiboLogin() {
		try {
			Oauth oauth = new Oauth();

			// 如果没有提供Code,去往新浪登陆页面
			if (code == null) {
				String url = oauth.authorize("code");
				setRedirectUrl(url);
				return REDIRECT;
			}

			// 获取UID
			AccessToken accessToken = oauth.getAccessTokenByCode(code);
			Field field = AccessToken.class.getDeclaredField("uid");
			field.setAccessible(true);
			String uid = (String) field.get(accessToken);

			weiboUser = weiboUserBiz.getByUid(uid);

			if (weiboUser == null) {
				weiboUser = new WeiboUser();
				weiboUser.setUid(uid);
			}
			// 获得新浪用户信息
			Weibo weibo = new Weibo();
			weibo.setToken(accessToken.getAccessToken());
			Users users = new Users();
			weibo4j.model.User sinaWeiboUser = users.showUserById(uid);
			// 设置用户信息
			weiboUser.setExpireIn(accessToken.getExpireIn());
			weiboUser.setAccessToken(accessToken.getAccessToken());
			weiboUser.setName(sinaWeiboUser.getName());
			weiboUser.setAvatarLarge(sinaWeiboUser.getavatarLarge());
			weiboUser.setDescription(sinaWeiboUser.getDescription());
			weiboUser.setProfileImageUrl(sinaWeiboUser.getProfileImageUrl());
			weiboUserBiz.save(weiboUser);

			// 如果找不到对应的用户信息则新建一个
			if (weiboUser.getUser() == null) {
				user = new User();
				user.setWeiboUserId(weiboUser.getId());
				// 如果是一个新用户，则昵称设置为Weibo的Name
				user.setNick(weiboUser.getName());
				user.setUserName(weiboUser.getName());
				userBiz.save(user);
				// 保存新用户
				weiboUser.setUser(user);
				weiboUserBiz.save(weiboUser);

				name = weiboUser.getName();
				return INPUT;
			} else {
				// 如果为未注册状态
				user = userBiz.getByWeiboUserId(weiboUser.getId());
				if (!weiboUser.isRegistered()) {
					name = weiboUser.getName();
					return INPUT;
				} else {
					acceptLogin(user);
					return SUCCESS;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	/**
	 * 退出登陆
	 * 
	 * @return
	 */
	public String logout() {
		try {
			id = getCookie(SESSION_ID);
			oAuthBiz.deleteBySessionId(id);
			removeCookie(SESSION_ID);
			return ajax(Status.success, "退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ajax(Status.error, "退出登陆失败");
		}
	}

	/**
	 * 获得SessionID
	 * 
	 * @return
	 */
	public String getSessionId() {
		String sessionID = getCookie(SESSION_ID);
		if (sessionID == null) {
			sessionID = getRequest().getSession().getId();
		}
		return sessionID;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setoAuthBiz(OAuthBiz oAuthBiz) {
		this.oAuthBiz = oAuthBiz;
	}

	public void setWeiboUserBiz(WeiboUserBiz weiboUserBiz) {
		this.weiboUserBiz = weiboUserBiz;
	}

	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}

	public WeiboUser getWeiboUser() {
		return weiboUser;
	}

	public void setWeiboUser(WeiboUser weiboUser) {
		this.weiboUser = weiboUser;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public OAuth getOauth() {
		return oauth;
	}

	public void setOauth(OAuth oauth) {
		this.oauth = oauth;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public void setTemplateEmailService(
			TemplateEmailService templateEmailService) {
		this.templateEmailService = templateEmailService;
	}

	public String getVid() {
		return vid;
	}

	public void setVid(String vid) {
		this.vid = vid;
	}

	public void setEmailValidationBiz(EmailValidationBiz emailValidationBiz) {
		this.emailValidationBiz = emailValidationBiz;
	}
}
